//
//  TinyFortuneViewController.m
//  TinyFortune
//
//  Created by lc on 16/5/15.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "TinyFortuneViewController.h"
#import "tintyCell.h"
#import "tinyDataModel.h"
#import "TalkViewController.h"
#import "tinyFrameModel.h"
#import "bigPicViewController.h"
#import "AVFile +  getDictionary.h"
#import "comModel.h"


@interface TinyFortuneViewController ()<UITableViewDelegate,UITableViewDataSource,CustomIOSAlertViewDelegate>{
    NSString *_loversInvite;//加好友邀请
    UITableView *_commentTableView;
}

//数据数据源数组
@property (nonatomic,strong)UITableView *tinyFortuneTablel;
@property (nonatomic,strong)NSMutableArray *tinyData;
@property (nonatomic,strong)NSMutableArray *tinyFrame;


/**返回上传数据的ID*/
@property (nonatomic,strong)NSMutableArray *objectIdArray;
@end

@implementation TinyFortuneViewController
#pragma mark - 数据源数组懒加载
- (NSMutableArray *)objectIdArray{
    if (!_objectIdArray) {
        _objectIdArray = [NSMutableArray new];
    }
    return  _objectIdArray;
}
- (NSMutableArray *)tinyData{
    if (!_tinyData) {
        _tinyData = [NSMutableArray new];
    }else{
        [self sortArrayBytime:_tinyData];
    }
    return _tinyData;
}
- (NSMutableArray *)tinyFrame{
    if (!_tinyFrame) {
        _tinyFrame = [NSMutableArray new];
    }else{
        [self sortArrayBytime:_tinyFrame];
    }
    return  _tinyFrame;
}
#pragma  mark - 第一次加载
- (void)firstLoad{
    self.currentPage = 1 ;
    //首次的时候直接访问服务器的ID表单获取数据
    AVQuery *query = [AVQuery queryWithClassName:@"ID"];
    __weak typeof(self)weakSelf = self;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //懒加载自己的idArray
        [weakSelf.objectIdArray addObjectsFromArray:objects];
        [weakSelf sortArray:_objectIdArray];
        //每一次加载首先要对自己的idArray进行一次按时间排序(我写在了懒加载里)
        [_tinyFortuneTablel.mj_header beginRefreshing];
        
    }];
    
    
    
}
#pragma mark -排序
//按时间排序，最先发布的在最上面
- (void)sortArray:(NSMutableArray *)mArray{
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO];
    [mArray sortUsingDescriptors:@[sort]];
}
- (void)sortArrayBytime:(NSMutableArray *)mArray{
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    [mArray sortUsingDescriptors:@[sort]];
    
}
#pragma mark - 页面搭建
- (void)createUI{
    self.view.backgroundColor = [UIColor whiteColor];
    _tinyFortuneTablel = [[UITableView alloc]init];
    _tinyFortuneTablel.translatesAutoresizingMaskIntoConstraints = NO ;
    [self.view addSubview:_tinyFortuneTablel];
    //手写约束让，tableView与View四边对齐
    __weak typeof(self)weakSelf = self;
    [_tinyFortuneTablel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    _tinyFortuneTablel.delegate = self;
    _tinyFortuneTablel.dataSource = self ;
    
    //添加上拉刷新和下拉加载
    _tinyFortuneTablel.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _tinyFortuneTablel.mj_footer.hidden = YES ;
        self.currentPage = 1 ;
        [weakSelf requestDataWithCurrentPage:weakSelf.currentPage];
        
        
    }];
    _tinyFortuneTablel.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //隐藏header
        _tinyFortuneTablel.mj_header.hidden = YES;
        self.currentPage ++ ;
        [weakSelf requestDataWithCurrentPage:weakSelf.currentPage];
        
    }];
}
#pragma mark - 实现tableView协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.tinyFrame[indexPath.row] cellHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.tinyData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    tintyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[tintyCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    //设置点击不显示背景颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone ;
    cell.dataModel = self.tinyData[indexPath.row];
    cell.frameModel = self.tinyFrame[indexPath.row];
    
    return cell;
    
}
//MARK:实现点击cell弹出对应界面的功能
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    bigPicViewController *bigPic = [bigPicViewController new];
    
    //正向传值
    bigPic.objectID = self.objectIdArray[indexPath.row][@"ID"];
    bigPic.dataModel = self.tinyData[indexPath.row];
    bigPic.frameModel = self.tinyFrame[indexPath.row];
    [bigPic setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:bigPic animated:YES];
    
}
#pragma mark - 弹出框点击事件
- (void)customIOS7dialogButtonTouchUpInside:(id)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"Button Clicked! %d", (int)buttonIndex);
    //匹配成功
    if (buttonIndex == 0) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        MBProgressHUD *hud =[MBProgressHUD HUDForView:self.view];
        
        //第一步,给当前用户的情侣字段，增加一个相应的字段
        AVUser *user = [AVUser currentUser] ;
        [user setObject:_loversInvite forKey:@"lovers"];
        [user save];
        //第二步,同时生成一个新的表单，新进入的用户还要去遍历这个表单，来达到增加情侣的目的
        AVObject *loversObj = [[AVObject alloc]initWithClassName:@"responseLover"];
        [loversObj setObject:_loversInvite forKey:@"Id"];
        [loversObj setObject:user.mobilePhoneNumber forKey:@"myId"];
        [loversObj saveInBackground];
        //第三步,最后一定要删除这个好友邀请去
        AVQuery *qu = [AVQuery queryWithClassName:@"lovers"];
        [qu whereKey:@"Id" equalTo:user.mobilePhoneNumber];
        [qu findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            AVObject *obj =(AVObject *) objects.firstObject;
            [obj deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    CustomIOSAlertView *alert = (CustomIOSAlertView *)alertView;
                    [hud hide:YES];
                    [alert close];
                }else{
                    NSLog(@"%@",error.localizedDescription);
                }
            }];
        }];
        
    }else{
        CustomIOSAlertView *alert = (CustomIOSAlertView *)alertView;
        [alert close];
    }
    
}
#pragma mark - 弹出框
- (UIView *)createAlert{
    UIView *View = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 200)];
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"mobilePhoneNumber" equalTo:_loversInvite];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        //头像
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(105, 50, 70, 70)];
        AVUser *user = (AVUser *)objects.firstObject;
        NSDictionary *dict = [AVFile fileWithDictionary:[user objectForKey:@"iconImage"]];
        [imageView sd_setImageWithURL:dict[@"url"] placeholderImage:[UIImage imageNamed:@"default_avatar"]];
        imageView.layer.cornerRadius = 35 ;
        imageView.layer.masksToBounds = YES ;
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 130, 150, 20)];
        nameLabel.text = [user objectForKey:@"username"];
        UILabel *tLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 150, 150, 20)];
        tLabel.text = @"请求添加你为情侣";
        [View addSubview:tLabel];
        [View addSubview:nameLabel];
        [View addSubview:imageView];
        
        
    }];
    
    
    return View;
}
#pragma mark - 生命周期
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    AVUser *user = [AVUser currentUser];
    if (user) {
       
        
        AVQuery *cancelQuery = [AVQuery queryWithClassName:@"cancelLover"];
        [cancelQuery whereKey:@"Id" equalTo:user.mobilePhoneNumber];
        [cancelQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (objects.count > 0 ) {
                NSLog(@"删除配对中");
                AVObject *obje = objects.firstObject;
                [user setObject:nil forKey:@"lovers"];
                [user saveInBackground];
                [obje deleteInBackground];
                [[DatabaseManager defaultManager] deleteAllObject:[comModel class]];
                [[DatabaseManager defaultManager] deleteAllObject:[AVIMTextMessage class]];
                [[DatabaseManager defaultManager] deleteAllObject:[AVIMAudioMessage class]];

            }
            
            
        }];

        
        //遍历lovers表单，获取加好友的弹框
        AVQuery *query = [AVQuery queryWithClassName:@"lovers"];
        [query whereKey:@"Id" equalTo:[AVUser currentUser].mobilePhoneNumber];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (objects.count > 0 ) {
                AVObject *object =  objects.firstObject ;
                
                _loversInvite = [object objectForKey:@"myId"];
                CustomIOSAlertView *alert = [CustomIOSAlertView new];
                [alert setContainerView:[self createAlert]];
                [alert setButtonTitles:[NSMutableArray arrayWithObjects:@"确定", @"取消", nil]];
                //协议
                [alert setDelegate:self];
                [alert setUseMotionEffects:true];
                [alert show];
            }
        }];
        //遍历responseLover这个表单，如果有就表示对方已经接受了那么就达到情侣匹配的目的，因为别个User无法更改自己的键值,所以只能用两个表单的方法
        AVQuery *responseQuery = [AVQuery queryWithClassName:@"responseLover"];
        [responseQuery whereKey:@"Id" equalTo:[AVUser currentUser].mobilePhoneNumber];
        [responseQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            if (objects.count > 0 ) {
                AVObject *object =  objects.firstObject ;
                [user setObject:[object objectForKey:@"myId"] forKey:@"lovers"];
                [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        
                    }else{
                        NSLog(@"%@",error.localizedDescription);
                    }
                }];
                [object deleteInBackground];
            }
        }];
           }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self firstLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationAction:) name:@"objectId" object:nil];
}
#pragma mark - 观察着模式，接收到消息的改变
- (void)notificationAction:(NSNotification *)notification{
    
    __weak typeof(self)weakSelf = self;
    //得到当前发送的ID
    NSDictionary *dict =[notification userInfo];
    NSString *objectID = dict[@"objectId"];
    //且id数组也要增加,不然新添加的不会再刷新后显示在页面上
    [self.objectIdArray addObject:[notification userInfo]];
    [AVFile getFileWithObjectId:objectID withBlock:^(AVFile *file, NSError *error) {
        NSDictionary *dict = [AVFile fileWithDictionary:file];
        tinyDataModel *data = [[tinyDataModel alloc]initWithDict:dict];
        tinyFrameModel *frame = [tinyFrameModel new];
        frame.dataModel = data;
        [weakSelf.tinyData addObject:data];
        [weakSelf.tinyFrame addObject:frame];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //吧新发布的说说插入在最上面
            [weakSelf.tinyFortuneTablel beginUpdates];
            NSMutableArray *indexPaths = [NSMutableArray new];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [indexPaths addObject:indexPath];
            [weakSelf.tinyFortuneTablel insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
            [weakSelf.tinyFortuneTablel endUpdates];
        });
    }];
    
    //=============从新刷新OBJectID数组里面的数据
    AVQuery *query = [AVQuery queryWithClassName:@"ID"];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //懒加载自己的idArray
        [weakSelf.objectIdArray removeAllObjects];
        [weakSelf.objectIdArray addObjectsFromArray:objects];
        [weakSelf sortArray:_objectIdArray];
    }];
    
    
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 请求数据
- (void)requestDataWithCurrentPage:(NSInteger)currentPage{
    //模拟一个通过页数来控制刷新个数的方法
    int temp = (self.currentPage - 1) *page ;
    for (int i = temp ; i <self.currentPage * page && i < self.objectIdArray.count ; i++) {
        [self requestDataWithObjectId:self.objectIdArray[i][@"ID"]];
        
    }
    
    
}

- (void)requestDataWithObjectId:(NSString *)objectId{
    
    __weak typeof(self)weakSelf = self ;
    [AVFile getFileWithObjectId:objectId withBlock:^(AVFile *file, NSError *error) {
        
        if (file) {
            //利用YYmodel解析出json格式的字典
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:file.yy_modelToJSONData options:NSJSONReadingMutableContainers error:nil];
            tinyDataModel *dataModel = [[tinyDataModel alloc]initWithDict:dict];
            //判断当前页数是否为1,首次刷新,下拉加载
            //上拉是刷新,下来是加载, 每次上拉都是从 1开始,为了防止重复，才清空的,然后由于我是模拟这个效果,我的for循环要循环4次,这样有3个数据会被清空掉,加上另外一个条件就可以了（前3个数据不会被清空）
            if(weakSelf.currentPage == 1 && weakSelf.tinyData.count >= 4){
                [weakSelf.tinyData removeAllObjects];
                [weakSelf.tinyFrame removeAllObjects];
            }
            //实现赋值
            [weakSelf.tinyData addObject:dataModel];
            tinyFrameModel *frameModel = [tinyFrameModel new];
            frameModel.dataModel = dataModel ;
            [weakSelf.tinyFrame addObject:frameModel];
            [weakSelf.tinyFortuneTablel reloadData];
            
            //异步刷新视图
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新数据
                [weakSelf.tinyFortuneTablel reloadData];
                //更新header footer
                [weakSelf.tinyFortuneTablel.mj_header endRefreshing];
                [weakSelf.tinyFortuneTablel.mj_footer endRefreshing];
                weakSelf.tinyFortuneTablel.mj_footer.hidden = NO;
                weakSelf.tinyFortuneTablel.mj_header.hidden = NO;
                // 处理全部加载完成的情况
                if (weakSelf.objectIdArray.count <= weakSelf.tinyData.count) {
                    //数据全部请求完毕
                    [weakSelf.tinyFortuneTablel.mj_footer endRefreshingWithNoMoreData];
                }//当你数据还不够多时，重置footer的状态
                else{
                    [weakSelf.tinyFortuneTablel.mj_footer resetNoMoreData];
                }
                
            });
            
        }else{
            [KVNProgress showErrorWithStatus:error.localizedDescription];
        }
        
    }
     
     
     ];
    
}


@end
